package cn.sheep.sense;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 * author: sheep.Old
 * qq: 64341393
 * Created 2018/5/31
 */
public class ProviderServer {

    // 定义zk根节点
    static final String pZnode = "/servers";
    static final String ZKSERVER = "demo01:2181,demo02:2181,demo03:2181";
    static final int TIMEOUT = 2000;

    ZooKeeper zk = null;

    public static void main(String[] args) {
        try {
            String port = args[0];
            ProviderServer server = new ProviderServer();
            //1. 连接zk
            server.connectZookeeper();
            //2. 注册自己
            server.registerSelf(port);
            //3. 等待客户端的调用
            server.handlerService(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接受客户端发送过来的请求
     */
    private void handlerService(String port) throws IOException {
        ServerSocket socket = new ServerSocket(Integer.parseInt(port));
        while (true) {
            Socket accept = socket.accept();
            // TODO 启动一个线程用来处理客户端发送过来的请求 ...
            // 根据需求做相应的处理。
        }

    }

    /**
     * 向zk注册自己
     */
    private void registerSelf(String port) throws Exception {
        ArrayList<ACL> acls = ZooDefs.Ids.OPEN_ACL_UNSAFE;
        //判断节点是否存在，不存在创建它。
        if (null == zk.exists(pZnode, false)) {
            zk.create(pZnode, "online node list".getBytes(),acls, CreateMode.PERSISTENT);
        }
        //获取主机名
        String hostName = InetAddress.getLocalHost().getHostName();
        //在Zookeeper上创建节点，及节点数据（主机名:端口号）。
        zk.create(pZnode+"/server", (hostName+":"+port).getBytes(), acls, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("成功的向zk注册了 = " + hostName);
    }

    /**
     * 连接zk
     */
    private void connectZookeeper() throws IOException {
        zk = new ZooKeeper(ZKSERVER, TIMEOUT, null);
    }


}
